<?php
namespace WDB\Query\Element;
use WDB,
    WDB\Exception;

/**
 * Query logic operator
 * 
 * @author Richard Ejem <richard(at)ejem.cz>
 * @package WDB
 */
abstract class InfixOperator extends WDB\BaseObject implements iElement
{
    protected $op;
    protected $expressions;
    
    /**
     * Chain more expressions to this operator. not supported by unary operators
     *
     * @param iExpression|array $expr1,...
     * @return self
     * @throws Exception\InvalidOperation for descendant classes that cannot be chained
     */
    public function addExpression($expr1)
    {
        $this->expressions = array_merge($this->expressions, WDB\Utils\Arrays::linearize(func_get_args()));
        return $this;
    }
    
    public function getOperator()
    {
        return $this->op;
    }
    
    public function getExpressions()
    {
        return $this->expressions;
    }
    
    public static function create($expressions, $op)
    {
        if (in_array($op, ExprOperator::$supportedOps))
        {
            return new ExprOperator($expressions, $op);
        }
        if (in_array($op, LogicOperator::$supportedOps))
        {
            return new LogicOperator($expressions, $op);
        }
        if (in_array($op, Compare::$supportedOps))
        {
            if (count($expressions) != 2)
            {
                throw new Exception\BadArgument("Compare operators must have exactly two operands.");
            }
            return new Compare($expressions[0], $expressions[1], $op);
        }
        throw new Exception\BadArgument("Invalid operator: $op");
    }

        
    public function __construct($expressions, $op)
    {
        $this->expressions = WDB\Utils\Arrays::linearize($expressions);
        $this->op = $op;
    }
}
